package com.wxxymakers.cklabrecruit.realm;

import com.wxxymakers.cklabrecruit.entity.User;
import com.wxxymakers.cklabrecruit.entity.enum_.Role;
import com.wxxymakers.cklabrecruit.service.UserService;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.StringUtils;

/**
 * @AUTHOR soft
 * @DATE 2018/10/26 16:59
 * @DESCRIBE
 */
@Slf4j
public class AuthrcRealm extends AuthorizingRealm {

    @Setter
    private UserService userService;

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Object principal = principals.getPrimaryPrincipal();
        User   user      = userService.getByUsername((String) principal);
        info.addRole(Role.STUDENT.getName());
        if (user.getRole().equals(Role.ADMIN)) {
            info.addRole(Role.ADMIN.getName());
        }
        return info;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        User   user     = userService.getByUsername(username);
        if (StringUtils.isEmpty(username) || user == null) {
            throw new UnknownAccountException("未知用户！");
        }
        ByteSource source   = ByteSource.Util.bytes(username);
        String     password = user.getPassword();
        return new SimpleAuthenticationInfo(username, password, source, getName());
    }

    /*public static void main(String[] args) {
        ByteSource source = ByteSource.Util.bytes("cklab");

        SimpleHash hash = new Md5Hash("123456", source, 101);

        System.out.println(hash.toHex());

    }*/
}
